package com.uphone.kingmall.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.LogUtils;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.uphone.kingmall.activity.order.AllOrderActivity;
import com.uphone.kingmall.activity.personal.set.AddressListActivity;
import com.uphone.kingmall.adapter.SettleAdapter0;
import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.PayAliCallbackBean;
import com.uphone.kingmall.bean.PayResult;
import com.uphone.kingmall.bean.PayWxCallbackBean;
import com.uphone.kingmall.bean.SettleCartBean;
import com.uphone.kingmall.bean.SubmitOrderBean;
import com.uphone.kingmall.bean.UserAddrBean;
import com.uphone.kingmall.bean.UserDefaultAddr;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.main.MainActivity;
import com.uphone.kingmall.utils.ActivityCollector;
import com.uphone.kingmall.utils.AppUtil;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentData;
import com.uphone.kingmall.view.dialog.RadishDialog;
import com.uphone.kingmall.wxapi.WXPayEntryActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <pre>
 *     author : radish
 *     e-mail : 15703379121@163.com
 *     time   : 2019/3/20
 *     desc   :
 * </pre>
 */
public class SettleActivity0 extends BaseActivity {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    @BindView(R.id.rv_goods)
    RecyclerView rvGoods;
    @BindView(R.id.rb_ali)
    RadioButton rbAli;
    @BindView(R.id.rb_wchat)
    RadioButton rbWchat;
    @BindView(R.id.rb_union)
    RadioButton rbUnion;
    @BindView(R.id.rb_wallet)
    RadioButton rbWallet;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.rg_pay)
    RadioGroup rgpay;
    private SettleAdapter0 settleAdapter;
    @IntentData
    String jsonStr = "";
    private SettleCartBean cartBean;
    private int addId = -1;
    private double totalMoney;
    private SubmitOrderBean submitOrderBean;
    private RadishDialog payDialog;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_settle0;
    }

    @Override
    public void initView() {
        CommonUtil.initTitle(this, "结算", ll);
        rvGoods.setLayoutManager(new LinearLayoutManager(this));
        settleAdapter = new SettleAdapter0(this, new SettleAdapter0.OnShopItemClickListener() {
            @Override
            public void calculationPrice(int position, final SettleCartBean.ShopGoodsBean item) {
                // 计算总价格
                if (cartBean != null && cartBean.getShopGoods() != null && cartBean.getShopGoods().size() > position) {
                    cartBean.getShopGoods().set(position, item);
                    calculationTotalMoney();
                }
            }
        });
        rvGoods.setAdapter(settleAdapter);

        initListener();
        rgpay.check(R.id.rb_ali);
    }

    public void setRecycle(int height) {
        LogUtils.e("高度：" + height);
        ViewGroup.LayoutParams params = rvGoods.getLayoutParams();
        params.height = height;
        rvGoods.setLayoutParams(params);
    }

    private void initListener() {
    }

    @Override
    public void initData() {
        LogUtils.e("jsonStr:" + jsonStr);
        if (!TextUtils.isEmpty(jsonStr)) {
            cartBean = GsonUtils.getGson().fromJson(jsonStr, SettleCartBean.class);
            if (cartBean != null) {
                List<SettleCartBean.ShopGoodsBean> shopGoodList = cartBean.getShopGoods();
                if (shopGoodList != null) {
                    settleAdapter.setNewData(cartBean.getShopGoods());
                }
            }
        }
        OkGoUtils.normalRequest(MyUrl.getUserDefaultAddr, null, new onNormalRequestListener() {

            @Override
            public void onSuccess(String response, int code) {
                if (code == 0) {
                    UserDefaultAddr bean = GsonUtils.getGson().fromJson(response, UserDefaultAddr.class);
                    if (bean != null && bean.getDefaultAddr() != null) {
                        UserAddrBean defaultAddr = bean.getDefaultAddr();
                        tvName.setText("收货人：" + defaultAddr.getReceiver());
                        tvAddress.setText("收货地址：" + defaultAddr.getRegion() + defaultAddr.getAddress());
                        tvPhone.setText("" + defaultAddr.getTelephone());
                        addId = defaultAddr.getAddrId();
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    public void calculationTotalMoney() {
        LogUtils.e("计算价格");
        if (cartBean.getShopGoods() != null) {
            double totalFee = 0;
            for (int i = 0; i < cartBean.getShopGoods().size(); i++) {
                SettleCartBean.ShopGoodsBean shopGoodsBean = cartBean.getShopGoods().get(i);
                if (shopGoodsBean.isPost()) {
                    totalFee += shopGoodsBean.getPostFee();
                }
                if (shopGoodsBean.isScoreFeeSelect()) {
                    totalFee -= shopGoodsBean.getScoreRealFee();
                }
                if (shopGoodsBean.isYueFeeSelect()) {
                    totalFee -= shopGoodsBean.getYueDeductFee();
                }
            }
            totalMoney = totalFee + cartBean.getTotalFee();
            if (totalMoney < 0) {
                totalMoney = 0;
            }
            tvMoney.setText("¥" + (totalFee + cartBean.getTotalFee()));
        }
    }

    @OnClick({R.id.rl_address, R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_address:
                CommonUtil.startIntentType(this, AddressListActivity.class, 1);
                break;
            case R.id.tv_submit:
                submitOrder();
                break;
        }
    }

    private void submitOrder() {
        if (cartBean != null) {
            submitOrderBean = new SubmitOrderBean();
            String shopCarIds = "";
            boolean isPost = false;
            for (int i = 0; i < cartBean.getShopGoods().size(); i++) {
                SettleCartBean.ShopGoodsBean shopGoodsBean = cartBean.getShopGoods().get(i);
                for (int j = 0; j < shopGoodsBean.getGoods().size(); j++) {
                    SettleCartBean.ShopGoodsBean.GoodsBean goodsBean = shopGoodsBean.getGoods().get(j);
                    // 购物车id
                    if (cartBean.getCode() == 0) {
                        shopCarIds += goodsBean.getShopCarId() + ",";
                    }
                }
                // 快递与否
                if (shopGoodsBean.isPost()) {
                    isPost = true;
                }
            }
            if (isPost) {
                if (addId == -1) {
                    ToastUtils.showShortToast(this, "请填写收货地址！");
                    return;
                }
                submitOrderBean.setAddrId("" + addId);
            }
            if (shopCarIds.length() > 1) {
                submitOrderBean.setShopCarIds(shopCarIds.substring(0, shopCarIds.length() - 1));
            }
            if (rgpay.getCheckedRadioButtonId() == R.id.rb_wallet) {
                //钱包支付
                payDialog = DialogUtil.showDialogWalletPay(SettleActivity0.this, new DialogUtil.OnWalletPayDialogCallBack() {
                    @Override
                    public void callBack(RadishDialog dialog, View view, String psd) {

                        submitOrderBean.setPaypass(psd);
                        submitOrder2();
                    }
                });
//                IntentUtils.getInstance()
//                        .with(this, WalletPayPassActivity.class)
//                        .putString(ConstansUtils.PARA, WalletPayPassActivity.Pay)
//                        .putString("clazz", getClass().getName())
//                        .start();
            } else {
                submitOrder2();
            }

        }

    }

    private void submitOrder2() {
        submitOrderBean.setPayType("" + (rgpay.getCheckedRadioButtonId() == R.id.rb_ali ? 1 : (rgpay.getCheckedRadioButtonId() == R.id.rb_wchat ? 2 : 3)));
        submitOrderBean.setOrderFee("" + totalMoney);

        List<SubmitOrderBean.ShopsBean> shopsBeanList = new ArrayList<>();
        List<EditText> editTextList = settleAdapter.getEditTextList();
        for (int i = 0; i < cartBean.getShopGoods().size(); i++) {
            if (editTextList != null && editTextList.size() > i && editTextList.get(i).getText() != null) {
                cartBean.getShopGoods().get(i).setRemark(editTextList.get(i).getText().toString().trim());
            }
            shopsBeanList.add(new SubmitOrderBean.ShopsBean(cartBean.getShopGoods().get(i)));
        }
        submitOrderBean.setShops(shopsBeanList);
        HttpParams params = new HttpParams();
        params.put("order", GsonUtils.getGson().toJson(submitOrderBean));
        OkGoUtils.progressRequest(MyUrl.submitOrder, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 1) {
                    //0元支付
                    paySuccess();
                    return;
                }
                if (code != 0) {
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    String sign = jsonObject.getString("sign");
                    if (TextUtils.isEmpty(sign)) {
                        paySuccess();
                    } else {
                        if (rgpay.getCheckedRadioButtonId() == R.id.rb_ali) {
                            //支付宝支付
                            alipay(body);
                        } else if (rgpay.getCheckedRadioButtonId() == R.id.rb_wchat) {
                            // 微信支付
                            wxPay(body);
                        } else {
                            // 佣金支付
                            paySuccess();
                        }
                    }
                } catch (JSONException e) {
                    LogUtils.e("异常：" + e.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void wxPay(final String body) {
        AppUtil.checkWchat(this, new AppUtil.AppCheckCallback() {
            @Override
            public void callBack() {
                PayWxCallbackBean bean = GsonUtils.getGson().fromJson(body, PayWxCallbackBean.class);
                PayWxCallbackBean.SignBean sign = bean.getSign();
                PayReq request = new PayReq();
                request.appId = sign.getAppId();
                request.partnerId = sign.getPartnerId();
                request.prepayId = sign.getPrepayId();
                request.packageValue = sign.getPackageValue();
                request.nonceStr = sign.getNonceStr();
                request.timeStamp = sign.getTimeStamp();
                request.sign = sign.getSign();
                WXPayEntryActivity.activity = SettleActivity0.this;
                MyApplication.api.sendReq(request);
            }
        });

    }

    @Override
    public void wxPaySuccess() {
        super.wxPaySuccess();
        paySuccess();
    }

    private void alipay(final String body) {
        AppUtil.checkAli(this, new AppUtil.AppCheckCallback() {
            @Override
            public void callBack() {
                PayAliCallbackBean bean = GsonUtils.getGson().fromJson(body, PayAliCallbackBean.class);
                final String sign = bean.getSign();
                // 必须异步调用
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(SettleActivity0.this);
                        final Map<String, String> resultMap = alipay.payV2(sign, true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                PayResult result = new PayResult(resultMap);
                                String resultStatus = result.getResultStatus();
                                if (TextUtils.equals(resultStatus, "9000")) {
                                    LogUtils.e("handleMessage: 已经支付成功，支付成功");
                                    com.blankj.utilcode.util.ToastUtils.showShort("支付成功");
                                    paySuccess();
                                } else if (TextUtils.equals(resultStatus, "6001")) {
                                    LogUtils.e("handleMessage: 已经取消支付");
                                    com.blankj.utilcode.util.ToastUtils.showShort("支付取消");
                                } else {
                                    LogUtils.e("handleMessage: 未知状态");
                                    com.blankj.utilcode.util.ToastUtils.showShort(resultStatus);
                                }
                            }
                        });
                    }
                }).start();
            }
        });

    }

    private void paySuccess() {
        if (payDialog != null && payDialog.isShowing()) {
            payDialog.dismiss();
        }
        ToastUtils.showShortToast(SettleActivity0.this, "支付成功");
        ActivityCollector.removeAll(MainActivity.class);
        if (1 == submitOrderBean.getShops().get(0).getPostType()) {
            //快递
            CommonUtil.startIntentType(SettleActivity0.this, AllOrderActivity.class, 2);
        } else {
            //到店
            CommonUtil.startIntentType(SettleActivity0.this, AllOrderActivity.class, 3);
        }
    }

    @Override
    public void onPayPsdSuccess(String passWord) {
        super.onPayPsdSuccess(passWord);
        submitOrderBean.setPaypass(passWord);
        submitOrder2();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            if (data != null) {
                UserAddrBean addressBean = (UserAddrBean) data.getSerializableExtra("bean");
                if (addressBean != null) {
                    addId = addressBean.getId();
                    tvName.setText(addressBean.getReceiver() + "");
                    tvAddress.setText("" + addressBean.getRegion() + addressBean.getAddress());
                    tvPhone.setText("" + addressBean.getTelephone());
                }
            }
        }
    }
}
